package com.kcs.fxmargin.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.json.JSONObject;

import com.kcs.common.utils.Constant;
import com.kcs.fxmargin.action.form.LoginActionForm;
import com.kcs.fxmargin.model.TPreOrder;
import com.kcs.fxmargin.service.CommonService;
import com.kcs.fxmargin.service.PreOrderService;

/**
 * Servlet implementation class PreOrderServlet
 */
public class PreOrderServlet extends HttpServlet {
	private Logger log = Logger.getLogger(Constant.LOG_FX);
	
	private static final long serialVersionUID 	= 1L;
	private static final String CONTENT_TYPE 	= "text/html; charset=utf-8";	
	private PreOrderService service 			= new PreOrderService();
    private CommonService common 				= new CommonService();
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PreOrderServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        response.setContentType(CONTENT_TYPE);
        
        System.out.println("SetupCustomerInformationServlet : Start");
        
        LoginActionForm loginBean = null;
        
        try {
        	
        	HttpSession session = request.getSession();
        	
        	if(session == null) {
        		JSONObject json = new JSONObject();
                json.put("data", "to");
                json.write(out);
        	} else {
        		loginBean = (LoginActionForm) request.getSession().getAttribute(Constant.LOGIN_DATA_SESSION);
            	
            	String id			= request.getParameter("id");
            	String custInfoId 	= request.getParameter("custInfoId");
            	String cifNo		= request.getParameter("cifNo");
            	String orderNo 		= request.getParameter("orderNo");
            	String amount	  	= request.getParameter("amount");
            	String ccy1 		= request.getParameter("ccy1");
            	String ccy2 		= request.getParameter("ccy2");
            	String exchRate	  	= request.getParameter("exchRate");
            	String updateDate 	= request.getParameter("updateDate");
            	String action	  	= request.getParameter("action");
            	String userId		= "";
            	int rowVers			= Integer.parseInt(request.getParameter("rowVersion"));
            	String result		= "";
            	
            	if(loginBean != null) {
            		userId = loginBean.getUserId();
            	}
            	
            	System.out.println("id		 	= " + id);
            	System.out.println("custInfoId 	= " + custInfoId);
            	System.out.println("cifNo 		= " + cifNo);
            	System.out.println("orderNo 	= " + orderNo);
            	System.out.println("amount 	 	= " + amount);
            	System.out.println("ccy1 		= " + ccy1);
            	System.out.println("ccy2 		= " + ccy2);
            	System.out.println("exchRate 	= " + exchRate);
            	System.out.println("updateDate 	= " + updateDate);
            	System.out.println("updateBy 	= " + userId);
            	System.out.println("rowVersion 	= " + rowVers);		
            	System.out.println("action 	 	= " + action);
            	
            	TPreOrder preOrder = new TPreOrder();
            	
            	preOrder.setId(id);
            	preOrder.setCustInfoId(custInfoId);
            	preOrder.setCifNo(cifNo);
            	preOrder.setOrderNo(orderNo);
            	preOrder.setAmount(convertStringtoBigDecimal(amount));
            	preOrder.setCcy1(ccy1);
            	preOrder.setCcy2(ccy2);
            	preOrder.setExchRate(convertStringtoBigDecimal(exchRate));
            	preOrder.setActiveStatus("A");
            	preOrder.setRowVersion(rowVers);
            	preOrder.setCreateby(userId);
            	preOrder.setUpdateBy(userId);
            	
            	if("insert".equals(action)) result = service.insert(preOrder);
            	else if ("update".equals(action)){
            		
            		int rowVersion = common.getRowVersion(Constant.PRE_ORDER, preOrder.getId());
            		
            		if(rowVersion <= preOrder.getRowVersion()){
            			preOrder.setRowVersion(rowVersion + 1);
            			result = service.update(preOrder);
            		}else{
            			log.error("Concurrent Data Access." + Constant.PRE_ORDER + " [id = " + preOrder.getId() + "]");
            			result = "Dup";
            		}
            		
            	}
            	
            	JSONObject json = new JSONObject();
                json.put("data", result);
                json.write(out);
        	}
        	
        	
        } catch (Exception e) {
        	log.error(e);
            out.print("{\"status\": \"failed\", \"message\": \"" +
                      e.getMessage() + "\"}");
        } finally {
            out.close();
        }

        System.out.println("SetupCustomerInformationServlet : End");
	}
	
	private BigDecimal convertStringtoBigDecimal(String number) throws Exception {
		BigDecimal bigDecimal = new BigDecimal(0);
		
		if(number != null && !"".equals(number)) bigDecimal = new BigDecimal(number);
		
		return bigDecimal;
	}

}
